package com.tungse.study.chat;

import java.io.*;
import java.net.Socket;

public class ServerChatReaderThread extends Thread {

    private Socket socket;
    public ServerChatReaderThread(Socket socket) {
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            while (true) {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String msg;
                while ((msg = bufferedReader.readLine()) != null) {
                    //System.out.println("服务端接收到客户端发送的消息：" + msg);
                    sendMsg2All(msg);
                }
            }
        } catch (Exception e) {
            ServerChat.ALL_ONLINE_SOCKETS.remove(socket);
            System.out.println(socket + "客户端下线了");
        }
    }

    private void sendMsg2All(String msg) {
        ServerChat.ALL_ONLINE_SOCKETS.forEach((socket) -> {
            try {
                if(socket != this.socket){
                    PrintStream ps = new PrintStream(socket.getOutputStream())  ;
                    ps.println(msg);
                    ps.flush();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });

    }
}
